import React from 'react';
import { Button, Typography, Card, Space } from 'antd';
import { BugOutlined, ReloadOutlined, HomeOutlined } from '@ant-design/icons';

const { Title, Paragraph, Text } = Typography;

interface ErrorInfo {
    componentStack: string;
}

interface ErrorBoundaryState {
    hasError: boolean;
    error: Error | null;
    errorInfo: ErrorInfo | null;
    errorId: string;
}

interface ErrorBoundaryProps {
    fallback?: React.ComponentType<{error: Error; reset: () => void}>;
    onError?: (error: Error, errorInfo: ErrorInfo) => void;
    children: React.ReactNode;
}

class ErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundaryState> {
    constructor(props: ErrorBoundaryProps) {
        super(props);
        this.state = {
            hasError: false,
            error: null,
            errorInfo: null,
            errorId: ''
        };
    }

    static getDerivedStateFromError(error: Error): Partial<ErrorBoundaryState> {
        // 生成错误ID用于跟踪
        const errorId = `ERR-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
        return {
            hasError: true,
            error,
            errorId
        };
    }

    componentDidCatch(error: Error, errorInfo: ErrorInfo) {
        console.error('[ErrorBoundary] Caught an error:', {
            error,
            errorInfo,
            errorId: this.state.errorId,
            userAgent: navigator.userAgent,
            url: window.location.href,
            timestamp: new Date().toISOString()
        });

        // 调用错误处理回调
        this.props.onError?.(error, errorInfo);

        this.setState({
            error,
            errorInfo
        });
    }

    handleReset = () => {
        this.setState({
            hasError: false,
            error: null,
            errorInfo: null,
            errorId: ''
        });
    };

    handleReload = () => {
        window.location.reload();
    };

    handleGoHome = () => {
        window.location.href = '/';
    };

    render() {
        if (this.state.hasError) {
            // 如果提供了自定义fallback组件，使用它
            if (this.props.fallback) {
                const FallbackComponent = this.props.fallback;
                return <FallbackComponent error={this.state.error!} reset={this.handleReset} />;
            }

            // 默认错误页面
            return (
                <div style={{ 
                    minHeight: '60vh', 
                    display: 'flex', 
                    alignItems: 'center', 
                    justifyContent: 'center',
                    padding: '40px 20px'
                }}>
                    <Card style={{ maxWidth: 600, width: '100%' }}>
                        <div style={{ textAlign: 'center', marginBottom: 32 }}>
                            <BugOutlined style={{ 
                                fontSize: 64, 
                                color: '#ff4d4f',
                                marginBottom: 16
                            }} />
                            <Title level={2} style={{ color: '#ff4d4f', marginBottom: 8 }}>
                                页面出现错误
                            </Title>
                            <Text type="secondary" style={{ fontSize: 16 }}>
                                很抱歉，页面遇到了意外错误
                            </Text>
                        </div>

                        <div style={{ marginBottom: 24 }}>
                            <Paragraph>
                                我们已经记录了这个错误，开发团队会尽快处理。
                                您可以尝试刷新页面或返回首页继续使用。
                            </Paragraph>
                            <Text type="secondary" style={{ fontSize: 12 }}>
                                错误ID: {this.state.errorId}
                            </Text>
                        </div>

                        <Space size="middle" style={{ width: '100%', justifyContent: 'center' }}>
                            <Button 
                                type="primary" 
                                icon={<ReloadOutlined />}
                                onClick={this.handleReset}
                            >
                                重试
                            </Button>
                            <Button 
                                icon={<ReloadOutlined />}
                                onClick={this.handleReload}
                            >
                                刷新页面
                            </Button>
                            <Button 
                                icon={<HomeOutlined />}
                                onClick={this.handleGoHome}
                            >
                                返回首页
                            </Button>
                        </Space>

                        {process.env.NODE_ENV === 'development' && (
                            <details style={{ marginTop: 24 }}>
                                <summary style={{ 
                                    cursor: 'pointer', 
                                    padding: '8px 0',
                                    borderTop: '1px solid #f0f0f0',
                                    marginTop: 16
                                }}>
                                    <Text type="secondary">开发模式：查看错误详情</Text>
                                </summary>
                                <div style={{ 
                                    marginTop: 12,
                                    padding: 12,
                                    backgroundColor: '#f5f5f5',
                                    borderRadius: 4,
                                    fontFamily: 'Consolas, Monaco, monospace',
                                    fontSize: 12,
                                    maxHeight: 300,
                                    overflowY: 'auto'
                                }}>
                                    <div>
                                        <strong>错误信息:</strong><br />
                                        {this.state.error?.toString()}
                                    </div>
                                    {this.state.error?.stack && (
                                        <div style={{ marginTop: 8 }}>
                                            <strong>错误堆栈:</strong><br />
                                            <pre style={{ 
                                                margin: 0, 
                                                whiteSpace: 'pre-wrap',
                                                wordBreak: 'break-word'
                                            }}>
                                                {this.state.error.stack}
                                            </pre>
                                        </div>
                                    )}
                                    {this.state.errorInfo?.componentStack && (
                                        <div style={{ marginTop: 8 }}>
                                            <strong>组件堆栈:</strong><br />
                                            <pre style={{ 
                                                margin: 0, 
                                                whiteSpace: 'pre-wrap',
                                                wordBreak: 'break-word'
                                            }}>
                                                {this.state.errorInfo.componentStack}
                                            </pre>
                                        </div>
                                    )}
                                </div>
                            </details>
                        )}
                    </Card>
                </div>
            );
        }

        return this.props.children;
    }
}

export default ErrorBoundary;